import React, { useState, useEffect, useRef } from 'react';
import { Box, Stack, Grid, Menu, MenuItem } from '@mui/material';
import GitHubIcon from '@mui/icons-material/GitHub';
import { useNavigate } from 'react-router-dom';
import { useAuth } from 'contexts/AuthContext';
import { motion, useAnimation } from 'framer-motion';
// Import the extracted StyledButton component
import StyledButton from 'components/objects/StyledButton';

const AnimatedFooter = ({ darkMode = false }) => {
  const navigate = useNavigate();
  const footerRef = useRef(null);
  const footerControls = useAnimation();
  const buttonsControls = useAnimation();
  const [footerVisible, setFooterVisible] = useState(false);
  const [menuOpened, setMenuOpened] = useState(false);
  const [menuItemClicked, setMenuItemClicked] = useState(false);
  
  // Using useRef for scroll info to avoid conflicts with other components
  const scrollInfoRef = useRef({
    lastScrollTop: 0,
    lastDirection: 'none'
  });

  // Get user from auth context with empty object fallback for safety
  const { user = {} } = useAuth();
  
  // Check if user is admin or superadmin
  const isAdmin = user?.role === 'admin' || user?.isAdmin === true || user?.role === 'superadmin';
  
  // For managing dropdown menus
  const [anchorEls, setAnchorEls] = useState({
    publicRoutes: null,
    publicAPIs: null,
    additionalPublicRoutes: null,
    githubLinksAndResources: null,
    authRoutes: null,
    privateRoutes: null
  });

  // Reset menuItemClicked after navigation
  useEffect(() => {
    if (menuItemClicked) {
      const timer = setTimeout(() => {
        setMenuItemClicked(false);
      }, 500);
      
      return () => clearTimeout(timer);
    }
  }, [menuItemClicked]);

  // Set up scroll event listener for the specific container
  useEffect(() => {
    const scrollableContainer = document.getElementById('scrollable-container');
    
    if (!scrollableContainer) {
      console.warn('Scrollable container not found. AnimatedFooter scroll animations may not work.');
      return () => {}; // Return empty cleanup function if no container
    }
    
    // Initial setup - footer is off-screen
    if (footerRef.current) {
      footerControls.set({ y: '100%', opacity: 0 });
      buttonsControls.set({ y: 50, opacity: 0 });
    }
    
    // Local variables for scroll handling
    // eslint-disable-next-line
    let isScrolling = false;
    let scrollTimeout = null;
    
    const handleScroll = () => {
      // Don't change visibility while menu is open or menu item was just clicked
      if (menuOpened || menuItemClicked) return;
      
      // Calculate if we're near the bottom (within 10vh of the bottom)
      const isNearBottom = scrollableContainer.scrollHeight - scrollableContainer.scrollTop - scrollableContainer.clientHeight < window.innerHeight * 0.1;
      
      // If near bottom, hide the animated footer
      if (isNearBottom) {
        if (footerVisible) {
          buttonsControls.start("hidden").then(() => {
            footerControls.start({
              y: '100%',
              opacity: 0,
              transition: { 
                type: "spring", 
                stiffness: 70,
                damping: 14,
                mass: 1
              }
            }).then(() => {
              setFooterVisible(false);
            });
          });
        }
        return;
      }
      
      // Clear any pending timeout
      if (scrollTimeout) {
        clearTimeout(scrollTimeout);
      }
      
      // Set isScrolling flag
      isScrolling = true;
      
      const scrollTop = scrollableContainer.scrollTop;
      const scrollDirection = scrollTop > scrollInfoRef.current.lastScrollTop ? 'down' : 'up';
      scrollInfoRef.current.lastScrollTop = scrollTop;
      scrollInfoRef.current.lastDirection = scrollDirection;
      
      // When scrolling down and footer is not visible, show it
      if (scrollDirection === 'down' && !footerVisible) {
        setFooterVisible(true);
        
        // Animate footer in from bottom
        footerControls.start({
          y: 0,
          opacity: 1,
          transition: { 
            type: "spring", 
            stiffness: 70,
            damping: 14,
            mass: 1
          }
        }).then(() => {
          // After footer is visible, animate buttons in sequence
          buttonsControls.start("visible");
        });
      } 
      // When scrolling up and footer is visible, hide it
      else if (scrollDirection === 'up' && footerVisible) {
        // First reset buttons to hidden state
        buttonsControls.start("hidden").then(() => {
          // Then hide footer
          footerControls.start({
            y: '100%', 
            opacity: 0,
            transition: { 
              type: "spring", 
              stiffness: 70,
              damping: 14,
              mass: 1
            }
          }).then(() => {
            setFooterVisible(false);
          });
        });
      }
      
      // Set a timeout to detect when scrolling has stopped
      scrollTimeout = setTimeout(() => {
        isScrolling = false;
        
        // If near bottom, don't show the animated footer
        if (isNearBottom) return;
        
        // If we stopped scrolling and the last direction was down, 
        // make sure footer stays visible
        if (scrollInfoRef.current.lastDirection === 'down') {
          if (!footerVisible) {
            setFooterVisible(true);
            
            footerControls.start({
              y: 0,
              opacity: 1,
              transition: { 
                type: "spring", 
                stiffness: 70,
                damping: 14,
                mass: 1
              }
            }).then(() => {
              buttonsControls.start("visible");
            });
          }
        }
      }, 200); // Longer timeout to ensure detection
    };
    
    // Add scroll event listener with passive flag for performance
    scrollableContainer.addEventListener('scroll', handleScroll, { passive: true });
    
    // Clean up
    return () => {
      scrollableContainer.removeEventListener('scroll', handleScroll);
      if (scrollTimeout) {
        clearTimeout(scrollTimeout);
      }
    };
  }, [footerVisible, footerControls, buttonsControls, menuOpened, menuItemClicked]);

  const handleMenuOpen = (menuName) => (event) => {
    setAnchorEls({ ...anchorEls, [menuName]: event.currentTarget });
    setMenuOpened(true); // Set menu open state to prevent hiding while user interacts
  };

  const handleMenuClose = (menuName) => () => {
    setAnchorEls({ ...anchorEls, [menuName]: null });
    // Check if all menus are closed
    const allClosed = Object.values({ ...anchorEls, [menuName]: null }).every(val => val === null);
    if (allClosed) {
      setMenuOpened(false);
    }
  };

  const handleMenuItemClick = (path, menuName) => {
    // Set menuItemClicked to prevent footer from disappearing right after click
    setMenuItemClicked(true);
    navigateOpen(path);
    handleMenuClose(menuName)();
  };

  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const navigateOpen = (path) => {
    if (path.startsWith('http')) {
      navigatePage(path);
    } else {
      navigate(path);
    }
  };
  
  const publicRoutes = [
    { label: "Return home", path: "/home-page" },
    { label: "Splash page", path: "/" },
    { label: "Getting started", path: "/getting-started" },
    { label: "Adding a card", path: "/add-card" },
    { label: "Login Page", path: "/login-page" },
    { label: "Overview", path: "/overview" },
    { label: "Overview Alt", path: "/overview-alt" }
  ];

  const publicAPIs = [
    { label: "API Endpoints", path: "/api-endpoints" },
    { label: "Experimental APIs", path: "/experimental-apis" },
    { label: "Discover more", path: "/discover-more" },
    { label: "Subscriptions", path: "/subscriptions" },
    { label: "Dashboard Page", path: "/dashboard-page" },
    { label: "Routing libraries", path: "/routing-libraries" },
    { label: "Plans", path: "/plans" }
  ];

  const additionalPublicRoutes = [
    { label: "Dashboard Test", path: "/DashboardTest" },
    { label: "Integrations", path: "/integrations" },
    { label: "Teams Page", path: "/teams-page" },
    { label: "Callbacks", path: "/callbacks" },
    { label: "Stripe sessions", path: "/stripe-sessions" },
    { label: "Templates", path: "/templates" },
    { label: "Webhooks", path: "/webhooks" }
  ];

  const githubLinksAndResources = [
    { 
      label: "Go API", 
      path: "https://github.com/startersaas/startersaas-backend-go-api-main.git",
      icon: <GitHubIcon fontSize="small" />
    },
    { 
      label: "Node API", 
      path: "https://github.com/startersaas/startersaas-backend-node-api-main.git",
      icon: <GitHubIcon fontSize="small" />
    },
    { 
      label: "React API", 
      path: "https://github.com/startersaas/startersaas-frontend-react-spa.git",
      icon: <GitHubIcon fontSize="small" />
    },
    { label: "Cards", path: "/cards" },
    { label: "Payments", path: "/payments" },
    { label: "Trials", path: "/trials" },
    { label: "Subscribers", path: "/subscribers" },
    { label: "Admin", path: "/admin" },
    { label: "Users Page", path: "/users-page" },
    { label: "Usage with webhooks", path: "/webhooks-usage" }
  ];

  const authRoutes = [
    { label: "Login", path: "/auth/login", color: "primary" },
    { label: "Forgot Password", path: "/auth/forgot-password", color: "primary" },
    { label: "Resend Activation", path: "/auth/resend-activation", color: "primary" },
    { label: "Reset Password", path: "/auth/reset-password/:email", color: "primary" },
    { label: "Activate Account", path: "/auth/activate/:email", color: "primary" },
    { label: "Register", path: "/auth/register", color: "primary" }
  ];

  const privateRoutes = [
    { label: "Dashboard", path: "/dashboard", color: "secondary" },
    { label: "Teams", path: "/teams", color: "secondary" },
    { label: "Team Detail", path: "/teams/:teamId", color: "secondary" },
    { label: "User Teams", path: "/user-teams", color: "secondary" },
    { label: "Add Card", path: "/card/add", color: "secondary" },
    { label: "Subscribe Plan", path: "/plan/:planId/subscribe", color: "secondary" },
    { label: "Plan", path: "/plan", color: "secondary" },
    { label: "Edit User", path: "/user/edit", color: "secondary" },
    { label: "Edit Account", path: "/account/edit", color: "secondary" },
    { label: "Users", path: "/users", color: "secondary" },
    { label: "Create User", path: "/create-user", color: "secondary" },
    { label: "Edit User Detail", path: "/edit-user/:userId", color: "secondary" },
    { label: "User Detail", path: "/user/:userId", color: "secondary" }
  ];

  // Animated button variant - with staggered animation
  const buttonVariant = {
    hidden: { y: 50, opacity: 0 },
    visible: (i) => ({ 
      y: 0, 
      opacity: 1,
      transition: { 
        type: "spring", 
        stiffness: 100, 
        damping: 12,
        delay: i * 0.1 + 0.2
      }
    })
  };

  const renderAnimatedFooterContent = () => (
    <Grid container spacing={2}>
      {/* Column 1 - Public Routes */}
      <Grid item xs={6} sm={2}>
        <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
          <motion.div
            variants={buttonVariant}
            initial="hidden"
            animate={buttonsControls}
            custom={0}
          >
            <StyledButton onClick={handleMenuOpen('publicRoutes')}>
              Public
            </StyledButton>
          </motion.div>
          <Menu
            anchorEl={anchorEls.publicRoutes}
            open={Boolean(anchorEls.publicRoutes)}
            onClose={handleMenuClose('publicRoutes')}
          >
            {publicRoutes.map((item, index) => (
              <MenuItem
                key={index}
                onClick={() => handleMenuItemClick(item.path, 'publicRoutes')}
              >
                {item.label}
              </MenuItem>
            ))}
          </Menu>
        </Stack>
      </Grid>

      {/* Column 2 - Public APIs */}
      <Grid item xs={6} sm={2}>
        <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
          <motion.div
            variants={buttonVariant}
            initial="hidden"
            animate={buttonsControls}
            custom={1}
          >
            <StyledButton onClick={handleMenuOpen('publicAPIs')}>
              APIs
            </StyledButton>
          </motion.div>
          <Menu
            anchorEl={anchorEls.publicAPIs}
            open={Boolean(anchorEls.publicAPIs)}
            onClose={handleMenuClose('publicAPIs')}
          >
            {publicAPIs.map((item, index) => (
              <MenuItem
                key={index}
                onClick={() => handleMenuItemClick(item.path, 'publicAPIs')}
              >
                {item.label}
              </MenuItem>
            ))}
          </Menu>
        </Stack>
      </Grid>

      {/* Column 3 - Additional Public Routes */}
      <Grid item xs={6} sm={2}>
        <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
          <motion.div
            variants={buttonVariant}
            initial="hidden"
            animate={buttonsControls}
            custom={2}
          >
            <StyledButton onClick={handleMenuOpen('additionalPublicRoutes')}>
              Routes
            </StyledButton>
          </motion.div>
          <Menu
            anchorEl={anchorEls.additionalPublicRoutes}
            open={Boolean(anchorEls.additionalPublicRoutes)}
            onClose={handleMenuClose('additionalPublicRoutes')}
          >
            {additionalPublicRoutes.map((item, index) => (
              <MenuItem
                key={index}
                onClick={() => handleMenuItemClick(item.path, 'additionalPublicRoutes')}
              >
                {item.label}
              </MenuItem>
            ))}
          </Menu>
        </Stack>
      </Grid>

      {/* Column 4 - GitHub Links and Resources */}
      <Grid item xs={6} sm={2}>
        <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
          <motion.div
            variants={buttonVariant}
            initial="hidden"
            animate={buttonsControls}
            custom={3}
          >
            <StyledButton onClick={handleMenuOpen('githubLinksAndResources')}>
              GitHub
            </StyledButton>
          </motion.div>
          <Menu
            anchorEl={anchorEls.githubLinksAndResources}
            open={Boolean(anchorEls.githubLinksAndResources)}
            onClose={handleMenuClose('githubLinksAndResources')}
          >
            {githubLinksAndResources.map((item, index) => (
              <MenuItem
                key={index}
                onClick={() => handleMenuItemClick(item.path, 'githubLinksAndResources')}
              >
                {item.icon && <span style={{ marginRight: '8px', display: 'inline-flex' }}>{item.icon}</span>}
                {item.label}
              </MenuItem>
            ))}
          </Menu>
        </Stack>
      </Grid>

      {/* Column 5 - Auth Routes */}
      {(user?.id || isAdmin) && (
        <Grid item xs={6} sm={2}>
          <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
            <motion.div
              variants={buttonVariant}
              initial="hidden"
              animate={buttonsControls}
              custom={4}
            >
              <StyledButton onClick={handleMenuOpen('authRoutes')}>
                Auth
              </StyledButton>
            </motion.div>
            <Menu
              anchorEl={anchorEls.authRoutes}
              open={Boolean(anchorEls.authRoutes)}
              onClose={handleMenuClose('authRoutes')}
            >
              {authRoutes.map((item, index) => (
                <MenuItem
                  key={index}
                  onClick={() => handleMenuItemClick(item.path, 'authRoutes')}
                >
                  {item.label}
                </MenuItem>
              ))}
            </Menu>
          </Stack>
        </Grid>
      )}

      {/* Column 6 - Private Routes */}
      {(user?.id || isAdmin) && (
        <Grid item xs={6} sm={2}>
          <Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
            <motion.div
              variants={buttonVariant}
              initial="hidden"
              animate={buttonsControls}
              custom={5}
            >
              <StyledButton onClick={handleMenuOpen('privateRoutes')}>
                Private
              </StyledButton>
            </motion.div>
            <Menu
              anchorEl={anchorEls.privateRoutes}
              open={Boolean(anchorEls.privateRoutes)}
              onClose={handleMenuClose('privateRoutes')}
            >
              {privateRoutes.map((item, index) => (
                <MenuItem
                  key={index}
                  onClick={() => handleMenuItemClick(item.path, 'privateRoutes')}
                >
                  {item.label}
                </MenuItem>
              ))}
            </Menu>
          </Stack>
        </Grid>
      )}
    </Grid>
  );

  return (
    <motion.div
      ref={footerRef}
      initial={{ y: '100%', opacity: 0 }}
      animate={footerControls}
      style={{ 
        position: 'fixed',
        bottom: 0,
        left: 0,
        width: '100%',
        zIndex: 1,
        pointerEvents: footerVisible ? 'auto' : 'none' // Only allow interaction when visible
      }}
    >
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          backgroundColor: darkMode ? 'black' : 'white',
          background: 'transparent',
        }}
      >
        <Box
          sx={{
            width: {
              xs: '100%',
              sm: 600,
              md: 960,
              lg: 1280,
              xl: 1920,
            },
          }}
        >
          {renderAnimatedFooterContent()}
        </Box>
      </Box>
    </motion.div>
  );
};

export default AnimatedFooter;